<template>
  <div id="wrapper" style="padding: 20px">
    <el-form :model="backgroundPicture" status-icon label-width="100px" class="demo-ruleForm">
      <el-form-item label="背景图片" prop="backgroundPicture">
        <template slot-scope="porps">
          <el-upload
              class="avatar-uploader"
              :action="baseApi + '/api/common/file/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="backgroundPicture.url != '' && backgroundPicture.url != undefined" :src="backgroundPicture.url" class="backgroundPicture"/>
            <img v-else src="../../assets/login/image/bj.jpg" class="backgroundPicture"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </template>
      </el-form-item>
      <el-form-item align="right">
        <el-button type="primary" @click="saveBackgroundPicture()">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SystemConfiguration",
  data: function (){
    return {
      baseApi: process.env.BASE_API,
      backgroundPicture: {
        url: ''
      }
    }
  },
  methods: {
    /**
     * 图片上传成功回调
     * @param res
     */
    handleAvatarSuccess(res) {
      this.backgroundPicture.url = this.baseApi + res.data
    },
    /**
     * 对图片进行校验
     * @param file
     * @returns {boolean}
     */
    beforeAvatarUpload(file) {
      const isImg = this.checkImgType(file);
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isImg) {
        this.$message.error('上传背景图片只能是图片格式!');
      }
      if (!isLt10M) {
        this.$message.error('上传背景图片大小不能超过 10MB!');
      }
      return isImg && isLt10M;
    },
    /**
     * 判断是否为图片
     * @param file
     * @returns {boolean}
     */
    checkImgType(file){
      if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name) ) {
        return  false;
      }else{
        return true;
      }
    },
    /**
     * 获取背景图片
     * @returns {Promise<void>}
     */
    async getBackgroundPicture() {
      let res = await this.$http.get('/api/systemConfig/getLoginBackgroundPicture')
      if (res.code == 0) {
        this.backgroundPicture.url = res.data
      }
    },
    /**
     * 保存背景图片
     * @returns {Promise<void>}
     */
    async saveBackgroundPicture() {
      let res = await this.$http.post('/api/systemConfig/updateLoginBackgroundPicture', this.backgroundPicture)
      if (res.code == 0) {
        this.$message.success('修改成功');
      }
    }
  },
  created() {
    this.getBackgroundPicture()
  },
  mounted() {
    this.$bus.$on('page-refresh', name => {
      if (name === 'SystemConfiguration') {
        this.getBackgroundPicture()
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.backgroundPicture{
  width: 50em;
}
</style>
